#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>

#define LEFT    	0
#define RIGHT   	20
#define THRNUM  	20
#define FILENAME 	"/tmp/out"
#define BUFFSIZE 	1024

// 使用静态互斥量的方式，宏方式
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 

// 需要定义在main上面，负责找不到，或者先声明
static void *clacute(void *arg)
{
    FILE * fp;
	char buf[BUFFSIZE];

	fp = fopen(FILENAME, "r+");
	if(fp == NULL){
		perror("fopen()");
		exit(1);
	}
	
	/*
	 * 文件的读写需要，添加锁，谁拿到锁谁去执行，执行完毕释放锁
	 * */
	pthread_mutex_lock(&mutex);
	fgets(buf, BUFFSIZE, fp);
	fseek(fp, 0, SEEK_SET);
	fprintf(fp, "%d\n",atoi(buf)+1);
	fclose(fp);
	pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
	int i, err;
	pthread_t tids[THRNUM];

	for (i = LEFT; i < RIGHT; ++i) {
		err = pthread_create(tids + (i-LEFT), NULL, clacute, NULL);
		if (err) {
            fprintf(stderr, "pthread_create(): %s\n", strerror(err));
            exit(1);
        }	
	}

	for (i = LEFT; i < RIGHT; ++i) {
        pthread_join(tids[i-LEFT], NULL);
    }

	pthread_mutex_destroy(&mutex);

	exit(0);
}
